<?php
/**
 * CsvExporterActiveDataProvider
 *
 * PHP version 5
 *
 * @category
 * @package
 * @author   Evgeny Utehin <utehin@ebola.com.ua>
 */

class CsvExporterArrayDataProvider extends CsvExporterWorker
{
    protected function getReportHeaders()
    {
        $headers = array();

        if (!$this->_onlyIncluded) {
            foreach ($this->data[0] as $key => $value) {
                if (!in_array($key, $this->_excludedColumns)) {
                    $this->getHeader($headers, $key);
                }
            }
        }

        if (!empty($this->_includedColumns)) {
            foreach ($this->_includedColumns as $key => $value) {
                $this->getHeader($headers, $value, $key);
            }
        }

        return $headers;
    }

    protected function getHeader(&$headers, $value, $key = '')
    {
        if (is_array($value)) {
            if (isset($value['header'])) {
                array_push($headers, $value['header']);
            } else {
                array_push($headers, $key);
            }
        } else {
            array_push($headers, $value);
        }
    }

    protected function getReportBody($fp)
    {
        $documentRow = array();

        if ($this->onlyIncluded) {
            if (!empty($this->_data)) {
                foreach ($this->_data as $row) {
                    $this->getIncludedColumnsData($documentRow, $row);

                    fputcsv($fp, $documentRow, $this->delimiter, $this->enclosure);
                    $documentRow = array();
                }
            }
        } else {
            if (!empty($this->_data)) {
                foreach ($this->_data as $row) {
                    foreach ($row as $key => $value) {
                        if (!in_array($key, $this->_excludedColumns)) {
                            array_push($documentRow, $value);
                        }
                    }

                    $this->getIncludedColumnsData($documentRow, $row);

                    fputcsv($fp, $documentRow, $this->delimiter, $this->enclosure);
                    $documentRow = array();
                }
            }
        }
    }

    protected function getIncludedColumnsData(&$rowData, $row)
    {
        foreach ($this->_includedColumns as $key => $value) {
            if (is_array($value)) {
                array_push($rowData, $row[$key]);
            } else {
                array_push($rowData, $row[$value]);
            }
        }
    }
}
